/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/no-unused-state */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import StandardTable from '@/components/StandardTable';
import { connect } from 'dva';
import { Button, Row, Col, message } from 'antd';
import { debounce } from 'lodash';
import moment from 'moment/moment';
import ExpressInfoModal from '../ExpressInfoModal';
import DownLoadModal from '../DownLoadModal';
import OrderDetail from '../OrderDetail';
import pageConfig from '../orderPageConfig';

@connect(({ loading, orderRecord }) => ({
  orderRecord,
  getDetailList: loading.effects['orderRecord/getStatisticsDetailList'],
  yzDetailLoading: loading.effects['orderRecord/getOrderRecordDetail'],
}))
export default class Details extends Component {
  // eslint-disable-next-line react/sort-comp
  handleTableChange = debounce(
    pagination => {
      const { derivativePayload } = this.state;
      const { dispatch, record, formState, actionTypes, sourceType } = this.props;
      const { site_id, courier_name, time } = record;
      const { brand } = formState.formValues;
      let values;
      if (formState.isSearch) {
        // 判断是否有搜索过，无搜索用record值，有则用查询组件的值
        values = formState.formValues;
      } else {
        values = {
          site_id,
          brand,
          keyword: courier_name,
          start_time: time,
          end_time: time,
        };
      }

      if (sourceType == 'derivative') {
        values = {
          ...values,
          ...derivativePayload,
          page: pagination.current,
        };
      }

      this.setState({ page: pagination.current });
      dispatch({
        type: actionTypes.record,
        payload: {
          ...values,
          page: pagination.current,
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  static propTypes = {
    goBack: PropTypes.func,
  };

  constructor(props) {
    super(props);
    const { sourceType } = props;
    this.pageConfig = pageConfig.call(this, sourceType);
    const { OrderRecordColums } = this.pageConfig;
    this.state = {
      showDetail: false,
      expressInfo: null,
      waybill_no: null,
      formValues: null,
      type: 'record',
    };
    this.tableColum = OrderRecordColums;
    this.formRef = React.createRef();
  }

  componentDidMount() {
    const { dispatch, record, formState, actionTypes, sourceType } = this.props;
    const { site_id, cm_id, courier_name, time = '', data = {}, user = {} } = record;
    const { time: dataTiem = '' } = data;
    const { brand } = formState.formValues;
    const arr = time ? time.split('-') : dataTiem.split('-');
    const half = arr.length / 2;
    const timeArr = [arr.splice(0, half).join('-'), arr.join('-')];

    let payload = {
      site_id,
      brand,
      keyword: courier_name,
      start_time: timeArr[0],
      end_time: timeArr[1],
      page: 1,
    };

    if (sourceType === 'derivative') {
      payload = {
        ws_id: user.id,
        start_time: timeArr[0],
        end_time: timeArr[1],
        page: 1,
        is_new: 1,
        page_size: 100,
      };
      this.setState({
        derivativePayload: {
          ws_id: user.id,
          start_time: timeArr[0],
          end_time: timeArr[1],
          is_new: 1,
          page_size: 100,
        },
      });
    }

    if (sourceType === 'yz') {
      payload.site_id = cm_id;
      delete payload.brand;
      delete payload.keyword;
    }
    dispatch({
      type: actionTypes.record,
      payload,
    });
  }

  // 展示物流
  showExpressModal = record => {
    const { id, waybill_no, brand_name, data } = record;
    let expressInfo = {
      id,
      waybill_no,
      brand_name,
    };
    if (data) {
      expressInfo = {
        id: data.id,
        waybill_no: data.waybill_no,
        brand_name: data.brand_name,
      };
    }

    this.setState({
      expressInfo,
    });
  };

  toggleDetail = (bool, waybill_no, type, records) => {
    this.setState({
      showDetail: bool,
      waybill_no,
      type,
      records,
    });
  };

  // 添加下载任务
  addDownLoad = () => {
    const { dispatch, record, formState, sourceType, actionTypes = {} } = this.props;
    const { site_id, courier_name, time, user = {} } = record;
    const { brand } = formState.formValues;
    const { page } = this.state;
    const { addDownLoad } = actionTypes;
    const { start_time, end_time } = formState.formValues;
    let values;

    const diffDays = moment(end_time).diff(moment(start_time), 'day');
    if (diffDays >= 30) {
      message.error('只支持下载时间跨度一个月的记录！');
      return;
    }

    if (formState.isSearch) {
      // 判断是否有搜索过，无搜索用record值，有则用查询组件的值
      values = formState.formValues;
    } else {
      values = {
        site_id,
        brand,
        keyword: courier_name,
        start_time: time,
        end_time: time,
      };
    }
    if (sourceType == 'derivative') {
      values = {
        ws_id: user.id,
        start_time: formState.formValues.start_time,
        end_time: formState.formValues.end_time,
        page: 1,
        type: 4,
      };
    }
    if (sourceType == 'yz') {
      values.type = 6;
      values.start_time = formState.formValues.start_time;
      values.end_time = formState.formValues.end_time;
    }

    dispatch({
      type: addDownLoad,
      payload: {
        ...values,
        page,
      },
    });
  };

  // 查看下载任务
  checkDownLoadTask = () => {
    const { dispatch, sourceType, actionTypes = {} } = this.props;
    const { getDownLoadList } = actionTypes;
    const payload = {
      page: 1,
    };

    if (sourceType == 'derivative') {
      payload.type = 4;
    }
    if (sourceType == 'yz') {
      payload.type = 6;
    }

    dispatch({
      type: getDownLoadList,
      payload,
    });
    this.toggleModal(true);
  };

  toggleModal = open => {
    this.setState({ visible: open });
  };

  render() {
    const { expressInfo, showDetail, visible, waybill_no, records } = this.state;
    const {
      getOrderRecord,
      orderRecord: { orderRecordList },
      goBack,
      sourceType,
      yzDetailLoading,
    } = this.props;
    return (
      <div>
        {showDetail ? (
          <div>
            <OrderDetail id={waybill_no} sourceType={sourceType} records={records}>
              <Button type="primary" onClick={() => this.toggleDetail(false)}>
                返回
              </Button>
            </OrderDetail>
          </div>
        ) : (
          <div>
            <Row type="flex" gutter={[8, 8]} justify="space-between">
              <Col>
                <Row type="flex" gutter={[8]} style={{ marginBottom: 20 }}>
                  <Col>
                    <Button type="primary" onClick={this.addDownLoad}>
                      添加下载任务
                    </Button>
                  </Col>
                  <Col>
                    <Button type="primary" onClick={this.checkDownLoadTask}>
                      查看下载任务
                    </Button>
                  </Col>
                </Row>
              </Col>
              <Col>
                <Button type="primary" onClick={goBack}>
                  关闭明细
                </Button>
              </Col>
            </Row>
            <StandardTable
              rowKey={record => record.id || record.data.id}
              columns={this.tableColum}
              data={orderRecordList}
              loading={getOrderRecord || yzDetailLoading}
              onChange={this.handleTableChange}
              scroll={{ x: 800 }}
            />
            <ExpressInfoModal
              cleanData={() => {
                this.setState({
                  expressInfo: null,
                });
              }}
              data={expressInfo}
              type="orderRecord"
            />
            <DownLoadModal
              sourceType={sourceType}
              visible={visible}
              hideModal={() => this.toggleModal(false)}
              title="下载任务"
              type="record"
            />
          </div>
        )}
      </div>
    );
  }
}
